$(document).ready(function() {
  devrel.classifies.getAllTags(renderTags);
  devrel.classifies.getNewEntries(renderNextEntry);
});

function renderTags() {
  var c = devrel.classifies.tags.length;
  var corner = $('h1').offset();
  var top = corner.top + $('h1').width() / 2;
  var left = corner.left + $('h1').height() / 2;
  for (var i in devrel.classifies.tags) {
    var li = $('<li>').append($('<span class="contents">').text(devrel.classifies.tags[i]));
    $('ul').append(li);
    li.css('position', 'absolute');
    var angle = calculateDistributedAngle(i, c);
    var pos = calculatePosition(top, left, angle, 300);
    li.css('top', pos[0] - li.height() / 2);
    li.css('left', pos[1] - li.width() / 2);
  }
  
  $('li').draggable({
    revert: "invalid",
    start: function(event, ui) {
      $('li.selected').each(function() {
        $(this).removeClass('animate-movement');
        $(this).data('position', $(this).offset());
      })
    },
    drag: function(event, ui) {
      $('li.selected').each(function() {
        $(this).css('position', 'absolute')
        $(this).css('top', ui.offset.top + 20);
        $(this).css('left', ui.offset.left + 20);
        $(this).addClass('ui-droppable-hover');
      })
    },
    stop: function(event, ui) {
      $('li.selected').each(function() {
        $(this).addClass('animate-movement');
        $(this).css($(this).data('position'));
        $(this).removeClass('ui-droppable-hover');
      })
    }
  });
  $('li').click(function() {
    $(this).toggleClass('selected');
  })
}

function renderNextEntry() {
  var entry = devrel.classifies.getNextEntry();
  
  $('h1 > span').text(entry['data']);
  $('h1').droppable({
    hoverClass: 'ui-droppable-hover',
    drop: function(event, ui) {
      devrel.classifies.addTagToEntry(entry, ui.draggable.text());
      $('.selected').each(function() {
        devrel.classifies.addTagToEntry(entry, jQuery('span', this).text());
        $(this).removeClass('selected');
      });
      devrel.classifies.updateEntry(entry['id'], entry);
      $('li').remove();
      renderNextEntry();
      renderTags();
    }
  })
}

function calculateDistributedAngle(index, total) {
  return 2 * Math.PI / total * index;
}

function calculatePosition(centerTop, centerLeft, angle, radius) {
  var top = Math.sin(angle) * radius + centerTop;
  var left = Math.cos(angle) * radius + centerLeft;
  return [top, left];
}